﻿$(function () {
    //显示等待中
    $.showWaiting = function (message) {
        if ($("#message_waiting_pop").length > 0) {
            return;
        }
        var html = [];
        html.push("<div id='message_waiting_pop' class='pop-wrap'  style='background: transparent;'>");
        html.push("<div class='waiting'>");
        if (message) {
            html.push("<div class='msgtop1'></div>");
            html.push("<div class='spinner spinner1'>");
        } else {
            html.push("<div class='msgtop2'></div>");
            html.push("<div class='spinner spinner2'>");
        }
        html.push("<div class='bar1'></div>");
        html.push("<div class='bar2'></div>");
        html.push("<div class='bar3'></div>");
        html.push("<div class='bar4'></div>");
        html.push("<div class='bar5'></div>");
        html.push("<div class='bar6'></div>");
        html.push("<div class='bar7'></div>");
        html.push("<div class='bar8'></div>");
        html.push("<div class='bar9'></div>");
        html.push("<div class='bar10'></div>");
        html.push("<div class='bar11'></div>");
        html.push("<div class='bar12'></div>");
        html.push("</div>");
        if (message) {
            html.push("<div class='msgbottom1 waitingmessage'>" + message + "</div>");
        } else {
            html.push("<div class='msgbottom2'></div>");
        }
        html.push("</div>");
        html.push("</div>");
        html = html.join('');
        $(html).appendTo("body");
    }

    $.closeWaiting = function () {
        $("#message_waiting_pop").remove();
    }

    $.alert = function (message, alertCB, title, buttonCapture) {
        if ($("#message_alert_pop").length > 0) {
            return;
        }

        // 默认值
        if (!title) {
            title = "";
        }
        if (!message) {
            message = "";
        }
        if (!buttonCapture) {
            buttonCapture = "好";
        }

        var html = "<div id='message_alert_pop' class='pop-wrap'><div class='passwrod-bank-inp'><h2>{0}</h2><pre class='tishiyu'>{1}</pre><div class='pass-btn-block'><p class='queding1' id='btnalert0'>{2}</p></div></div></div>";

        html = html.format(title, message, buttonCapture);
        $(html).appendTo("body");

        $("#btnalert0").on("tap", function () {
            $("#message_alert_pop").remove();
            if (alertCB) alertCB(0);
        });
    };

    $.confirm = function (message, confirmCB, title, buttons) {
        if ($("#message_confirm_pop").length > 0) {
            return;
        }
        // 默认值
        if (!title) {
            title = "";
        }
        if (!message) {
            message = "";
        }
        if (!buttons) {
            buttons = ["确定", "取消"];
        } else if (buttons.length < 2) {
            $(alert(message, confirmCB, title, buttons[0]));
        }

        var html = "<div id='message_confirm_pop' class='pop-wrap' ><div class='passwrod-bank-inp' style='min-width: 17em;'><h2>{0}</h2><pre class='tishiyu'>{1}</pre><div class='pass-btn-block'><p class='queding' id='btnconfrim0'>{2}</p><p class='quxiao' id='btnconfrim1'>{3}</p></div></div></div>";
        html = html.format(title, message, buttons[0], buttons[1]);
        $(html).appendTo("body");

        var pop = $("#message_confirm_pop");
        $("#btnconfrim0").on("tap", function () {
            pop.remove();
            if (confirmCB) confirmCB(0);
        });
        $("#btnconfrim1").on("tap", function () {
            pop.remove();
            if (confirmCB) confirmCB(1);
        });
    };

    $.prompt = function (message, promptCB, title, tip, buttons) {
        if ($("#message_prompt_pop").length > 0) {
            return;
        }
        // 默认值
        if (!title) {
            title = "";
        }
        if (!message) {
            message = "";
        }
        if (!tip) {
            tip = "";
        }
        if (!buttons || buttons.length < 2) {
            buttons = ["确定", "取消"];
        }

        var html = "<div class='pop-wrap' id='message_prompt_pop'><div class='passwrod-bank-inp' style='min-width: 17em;'><h2>{0}</h2><pre class='tishiyu'>{1}</pre><p class='srxmk'><input type='text' id='message_prompt_input' class='qsrndxm' placeholder='{2}'></p><div class='pass-btn-block'><p class='queding' id='btnprompt0'>{3}</p><p class='quxiao' id='btnprompt1'>{4}</p></div></div></div>";
        html = html.format(title, message, tip, buttons[0], buttons[1]);
        $(html).appendTo("body");

        $("#message_prompt_input").focus();

        var pop = $("#message_prompt_pop");
        $("#btnprompt0").on("tap", function () {
            var value = $("#message_prompt_input").val();
            pop.remove();
            if (promptCB) promptCB(0, value);
        });
        $("#btnprompt1").on("tap", function () {
            var value = $("#message_prompt_input").val();
            pop.remove();
            if (promptCB) promptCB(1, value);
        });
    };

    $.toast = function (message, toastCB) {
        // 默认值
        if (!message) {
            message = "";
        }
        var options = {duration: 1000, top: "", left: ""};

        var html = "<div name='message_toast' class='pop-wrap' style='background: transparent;pointer-events: none;'><i class='toastmsg'>{0}</i></div>";
        html = html.format(message);
        $(html).appendTo("body");

        var msg = $("div[name=message_toast]");
        msg.fadeIn(1000);
        setTimeout(function () {
            msg.fadeOut(1200);
            setTimeout(function () {
                msg.remove();
                if(toastCB){
                  toastCB(0);
                }
            }, 1500);
        }, options.duration);
    };
});

/**
 * Github: https://github.com/BR0kEN-/jTap
 */
(function ($, _) {
    'use strict';
    var isTouch = "ontouchend" in document.createElement("div");
    var ev = {
        start: isTouch ? 'touchstart' : 'mousedown',
        end: isTouch ? 'touchend' : ' mouseup'
    };

    $.event.special[_] = {
        setup: function () {
            $(this).off('click').on(ev.start + ' ' + ev.end, function (e) {
                ev.E = e.originalEvent.changedTouches ? e.originalEvent.changedTouches[0] : e;
            }).on(ev.start, function (e) {

                if (e.which && e.which !== 1) {
                    return;
                }
                ev.target = e.target;
                ev.time = new Date().getTime();
                ev.X = ev.E.pageX;
                ev.Y = ev.E.pageY;
            }).on(ev.end, function (e) {
                if (
                    ev.target === e.target &&
                    ((new Date().getTime() - ev.time) < 750) &&
                    (ev.X === ev.E.pageX && ev.Y === ev.E.pageY)
                ) {

                    e.type = _;
                    e.pageX = ev.E.pageX;
                    e.pageY = ev.E.pageY;

                    $.event.dispatch.call(this, e);
                }
            });
        },
        remove: function () {
            $(this).off(ev.start + ' ' + ev.end);
        }
    };

    $.fn[_] = function (fn) {
        return this[fn ? 'on' : 'trigger'](_, fn);
    };
})(jQuery, 'tap');

(function (window) {
    /**
     * [dateDiff 算时间差]
     * @param  {[type=Number]} hisTime [历史时间戳，必传]
     * @param  {[type=Number]} nowTime [当前时间戳，不传将获取当前时间戳]
     * @return {[string]}         [string]
     */
    var dateDiff = function (hisTime, nowTime) {
        var now = nowTime ? nowTime : new Date().getTime(),
            diffValue = now - hisTime,
            minute = 1000 * 60, result = '',

            hour = minute * 60,
            day = hour * 24,
            halfamonth = day * 15,
            month = day * 30,
            year = month * 12,

            _year = diffValue / year,
            _month = diffValue / month,
            _week = diffValue / (7 * day),
            _day = diffValue / day,
            _hour = diffValue / hour,
            _min = diffValue / minute;

        if (_year >= 1) result = parseInt(_year) + "年前";
        else if (_month >= 1) result = parseInt(_month) + "个月前";
        else if (_week >= 1) result = parseInt(_week) + "周前";
        else if (_day >= 1) result = parseInt(_day) + "天前";
        else if (_hour >= 1) result = parseInt(_hour) + "个小时前";
        else if (_min >= 1) result = parseInt(_min) + "分钟前";
        else result = "刚刚";
        return result;
    }
    window.dateDiff = dateDiff
})(window);

/**
 * $.os
 * @param {type} $
 * @returns {undefined}
 */
(function ($, window) {
    function detect(ua) {
        this.os = {};
        var funcs = [

            function () { //wechat
                var wechat = ua.match(/(MicroMessenger)\/([\d\.]+)/i);
                if (wechat) { //wechat
                    this.os.wechat = {
                        version: wechat[2].replace(/_/g, '.')
                    };
                }
                return false;
            },
            function () { //android
                var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
                if (android) {
                    this.os.android = true;
                    this.os.version = android[2];

                    this.os.isBadAndroid = !(/Chrome\/\d/.test(window.navigator.appVersion));
                }
                return this.os.android === true;
            },
            function () { //ios
                var iphone = ua.match(/(iPhone\sOS)\s([\d_]+)/);
                if (iphone) { //iphone
                    this.os.ios = this.os.iphone = true;
                    this.os.version = iphone[2].replace(/_/g, '.');
                } else {
                    var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
                    if (ipad) { //ipad
                        this.os.ios = this.os.ipad = true;
                        this.os.version = ipad[2].replace(/_/g, '.');
                    }
                }
                return this.os.ios === true;
            }
        ];
        [].every.call(funcs, function (func) {
            return !func.call($);
        });
    }

    detect.call($, navigator.userAgent);
})(window, window);

//实现字符串trime
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

//实现字符串format功能
String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}

//实现Date的format功能例如：(new Date()).Format('yyyy-mm-dd hh:MM:ss');
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//timespan转换成时间字符串例如：toDateString(1442963412, 'yyyy-mm-dd hh:MM:ss')
function toDateString(timespan, fmt) {
    var newDate = new Date();
    newDate.setTime(timespan * 1000);
    return newDate.Format(fmt);
}

// 设置localstorage
function setLocalStorage(key, value) {
    localStorage.setItem(key, JSON.stringify(value));
}

// 读取localstorage
function getLocalStorage(key) {
    var obj = localStorage.getItem(key);
    if (obj) {
        return JSON.parse(obj);
    }
    return null;
}

//删除localstorage
function removeLocalStorage(key) {
    localStorage.removeItem(STORAGE_MANAGER.user);
}

// 设置sessionstorage
function setSessionStorage(key, value) {
    sessionStorage.setItem(key, JSON.stringify(value));
}

// 读取sessionstorage
function getSessionStorage(key) {
    var obj = sessionStorage.getItem(key);
    if (obj) {
        return JSON.parse(obj);
    }
    return null;
}

//删除sessionstorage
function removeSessionStorage(key) {
    sessionStorage.removeItem(key);
}

// 设置页面参数sessionstorage
function setPageParams(pagename, value) {
    sessionStorage.setItem(pagename, JSON.stringify(value));
}

// 读取页面参数(读取一次会删除)sessionstorage
function getPageParams(pagename) {
    var obj = sessionStorage.getItem(pagename);
    if (obj) {
        sessionStorage.removeItem(pagename);
        return JSON.parse(obj);
    }
    return null;
}


// 获取URL中参数
function getUrlParam(name, url) {
    var paramstr = url ? url.substr(url.lastIndexOf('?')) : window.location.search;
    paramstr = decodeURI(paramstr);
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = paramstr.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
}

// 获取跳转文件名
function getUrlFileName(strUrl) {
    var arrUrl = strUrl.split("/");
    var strPage = arrUrl[arrUrl.length - 1];

    return strPage;
}

// 生成唯一GUID
function NewGuid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());

    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
}

//  Sesssion_id 临时会话ID
function getSessionID() {
    var sessionid = getLocalStorage("session_id");
    if (!sessionid) {
        setLocalStorage("session_id", NewGuid());
    }

    return sessionid;
}

// 排除无需清理名单
var excludeStorage = [STORAGE_MANAGER.adslocatins,
    STORAGE_MANAGER.category,
    STORAGE_MANAGER.parentcategory,
    STORAGE_MANAGER.coinadslocatins,
    STORAGE_MANAGER.wgtversion,
    STORAGE_MANAGER.version];
// 清空本地缓存
function clearLocalStorage() {
    for (var i = 0; i < localStorage.length; i++) {
        var key = localStorage.key(i);
        if (excludeStorage.indexOf(key) > -1) {
            continue;
        }
        removeLocalStorage(key);
    }
}

/**
 * 获取图片路径
 * @param {URIString} key :图片id
 * @param {URIInt} width :图片宽度
 * @param {URIInt} height :图片高度
 **/
function getImageUrl(key, width, height) {
    // 依据商品的Key获取图片,格式：http://domain/{type}/{date}/{size}/{key}.jpg
    // 例如：http://d1.soolife.net/images/201403/180x180/53139babe36d21d81ea9cad373fded18.jpg
    if (!key) {
        return "http://d1.soolife.net/default.png";
    }
    if (!width) {
        width = 144;
    }
    if (!height) {
        height = 144;
    }
    // 缩放
    width = (width * CONFIG_MANAGER.imagezoom).toFixed(0);
    height = (height * CONFIG_MANAGER.imagezoom).toFixed(0);

    var datestr = new Date().Format("yyyyMM");
    var imageServers = CONFIG_MANAGER.imageServer;
    var maxnum = imageServers.length - 1;
    var randnum = getRandomNum(0, maxnum);

    return imageServers[randnum] + "/images/" + datestr + "/" + width + "x" + height + "/" + key + ".jpg";
}

// 产生随机数
function getRandomNum(min, max) {
    var range = max - min;
    var rand = Math.random();
    return (min + Math.round(rand * range));
}


(function (w) {
    // 空函数
    //默认true返回函数
    var returnTrue = function () {
        return true
    };
    //默认false返回函数
    var returnFalse = function () {
        return false
    };
    document.addEventListener('touchstart', returnFalse, false); //取消浏览器的所有事件，使得active的样式在手机上正常生效
    document.oncontextmenu = returnFalse; //屏蔽选择函数
    // H5 plus事件处理
    var ws = null,
        as = 'pop-in';

    function plusReady() {
        ws = plus.webview.currentWebview();
        // Android处理返回键
        plus.key.addEventListener('backbutton', function () {
            back();
        }, false);
    }

    if (w.plus) {
        plusReady();
    } else {
        document.addEventListener('plusready', plusReady, false);
    }

    // 处理返回事件
    w.back = function (hide) {
        if (w.plus) {
            ws || (ws = plus.webview.currentWebview());
            if (hide || ws.preate) {
                ws.hide('auto');
            } else {
                ws.close('auto');
            }
        } else if (history.length > 1) {
            history.back();
        } else {
            w.close();
        }
    };
    // 处理点击事件
    var openw = null,
        waiting = null;
    /**
     * 打开新窗口
     * @param {URIString} id : 要打开页面url
     * @param {boolean} wa : 是否显示等待框
     * @param {boolean} aniShow : 显示动画
     */
    w.redirect = function (id, wa, aniShow) {
    	console.log(id);
        if (openw) { //避免多次打开同一个页面
            return null;
        }
        if (w.plus) {
            wa && (waiting = plus.nativeUI.showWaiting());
            var pre = '';
            openw = plus.webview.create(encodeURI(pre + id), id, {
                scrollIndicator: 'none',
                scalable: false
            });
            if (!aniShow) {
                aniShow = "pop-in";
            }
//          openw.addEventListener('loaded', function () { //页面加载完成后才显示
                openw.show(aniShow);
                closeWaiting();
//          }, false);
            openw.addEventListener('close', function () { //页面关闭后可再次打开
                openw = null;
            }, false);
            return openw;
        } else {
            window.parent.window.location.href = encodeURI(id);
        }
        return null;
    };

    /**
     * 关闭等待框
     */
    w.closeWaiting = function () {
        waiting && waiting.close();
        waiting = null;
    }
})(window);